'use strict';
var jwt = require('jsonwebtoken');
const Controller = require('egg').Controller;

class LoginController extends Controller {
  async index() {
    const { userName, passWord } = this.ctx.request.body;
    const user = {
      id: '0001',
      name: 'admin',
      password: '123456'
    }

    if (user.name === userName && user.password === passWord) {
      this.ctx.session.userId = user.id;
      this.ctx.session.userName = user.name;
      const token = jwt.sign({ id: user.id }, 'aaa', { expiresIn: '1d' });
      this.ctx.cookies.set('token', token, {
        httpOnly: true, // 默认就是 true
        encrypt: true, // 加密传输
      });
      this.ctx.body = {
          retcode: 1,
          msg: '登录成功',
          userId: user.id
      };
    }
    else {
      this.ctx.body = {
          retcode: -1,
          msg: '用户名或密码错误'
      };
    }
  }

  async register() {
    const { username, password, email, phone } = this.ctx.request.body;
    if (username && password && email && phone) {
      this.ctx.body = {
        retcode: 1,
        msg: '注册成功（模拟注册，并不会创建真实账户哦～）'
      }
    }
    else {
      this.ctx.body = {
        retcode: -90002,
        msg: '注册失败'
      } 
    }
  }

  async getUser() {
    this.ctx.body = {
        userId: '0001',
        userName: 'admin'
    };
  }

  async logout() {
    this.ctx.session = null;
    this.ctx.cookies.set('token', '');
    this.ctx.body = {
        retcode: 1,
        msg: '登出成功'
    };
  }

  async redirect() {
    this.ctx.body = {
        retcode: -90001,
        msg: '未登录'
    };
  }
}

module.exports = LoginController;
